<template>
  <!-- <h2>供应商管理</h2> -->
  <zsearch v-loading="loading">
      <template #title>
        <span>供应商管理</span>
      </template>
      <template #date>
        <el-date-picker
            class="date-1"
            type="datetime"
            v-model="date"
            placeholder="选择日期"
            >
        </el-date-picker>
      </template>
      <template #select>
      </template>
      <template #btns>
        <el-button class="btn-1" @click="hanledSearch" v-jurisdiction="'warehouse:supplier:getSupplierPage'">查询</el-button>
			  <el-button class="btn-2">导出</el-button>
			  <el-button class="btn-2" @click="handleClickDrawer" v-jurisdiction="'warehouse:supplier:createSupplier'">新建供应商</el-button>
      </template>
      <template #table>
        <ztable 
          :tableData='data' 
          :strucs='groupData'
          width="120"
          :height="'100%'"
          :isshowOperation="true"
        >
        <template #default="slotScope">
          <el-button type="text" class="operation" @click="handleEditItem(slotScope.rowData)" v-jurisdiction="'warehouse:supplier:updateSupplier'">修改</el-button>
          <el-button type="text" class="operation" @click="handleDelItem(slotScope.rowData)" v-jurisdiction="'warehouse:supplier:delSupplier'">删除</el-button>
        </template>
        </ztable>
      </template>
      <template #page>
        <zpage 
            :currentPage="current" 
            :total="total" 
            :pageSize="size"
            @handleSizeChange="handleSizeChange" 
            @handleCurrentChange="handleCurrentChange"
        ></zpage>
      </template>
    </zsearch>

    <zdrawer size="40%" @handleClose="drawerClose('add')" title="新建供应商" v-model="showDrawer" >
      <template #body>
      <!-- 动态 -->
      <ztitleBorder title="基础信息">
        <div class="dynamic flex-wrap">
          <component :is="showWidget(item.type)" v-for="item in groupDataAdd" :key="item.name" :struc="item"  :passWidth="50"  />
        </div>
      </ztitleBorder>
      <!-- <ztitleBorder title="联系方式">
        <div class="dynamic f-w">
          <component :is="showWidget(item.type)" class="test" v-for="item in AddList" :key="item.name" :struc="item"  />
        </div>
      </ztitleBorder>
      <ztitleBorder title="公司三证">
        <div class="dynamic f-w">
          <component :is="showWidget(item.type)" class="test" v-for="item in AddList" :key="item.name" :struc="item"  />
        </div>
      </ztitleBorder>
      <ztitleBorder title="行业资质">
        <div class="dynamic f-w">
          <component :is="showWidget(item.type)" class="test" v-for="item in AddList" :key="item.name" :struc="item"  />
        </div>
      </ztitleBorder> -->
      </template>
      <template #footer>
        <el-button class="btn-2" @click="cancel('add')">取消</el-button>
        <el-button class="btn-1" @click="save('add')">保存资料</el-button>
      </template>
    </zdrawer>

    <!-- 修改 -->
    <zdrawer size="40%" @handleClose="drawerClose('edit')" title="修改供应商" v-model="showEditDrawer" >
      <template #body>
      <!-- 动态 -->
      <ztitleBorder title="基础信息">
        <div class="dynamic flex-wrap">
          <component :is="showWidget(item.type)" class="test" v-for="item in groupDataUpdate" :key="item.name" :struc="item" :passWidth="50"  />
        </div>
      </ztitleBorder>
      </template>
      <template #footer>
        <el-button class="btn-2" @click="cancel('edit')">取消</el-button>
        <el-button class="btn-1" @click="save('edit')">保存资料</el-button>
      </template>
    </zdrawer>
</template>

<script lang='ts'>
import { defineComponent, reactive, ref, toRefs, watch } from '@vue/runtime-core'
import ztable from '@components/Table/index.vue'
import zpage from '@components/pagination/pagination.vue'
import zsearch from '@components/search/search.vue'
import zdrawer from "@components/drawer/drawer.vue";
import ztitleBorder from "../../components/titleBorder/titleBorder.vue"

import useShowWidget from "../../components/widget/usechoose";

import useConfgin from '../../hook/getconfig'
import useUser from "../../hook/user";
import useRequet, { RespData } from "../../hook/network"
import { DataStruc } from "../../hook/datastruc";
import { debounce } from "../../utils/debounce"


import { useRouter } from "vue-router"
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'

const ID = 513
export default defineComponent({
  name: 'Supplier',
  components: {
    ztable,
    zpage,
    zsearch,
    zdrawer,
    ztitleBorder
  },
  setup() {
    const router = useRouter();
    const request = useRequet({ path: "" });
    const {groupData, groupDataAdd, groupDataUpdate} = useConfgin(ID)
     /** 列表部分 -> 开始 */
    let search = reactive({
      date:'',
      current: 1,
      size: 10,
      total: 0,
      id: null,
      loading: false
    })
    const data = ref([])
    console.log(groupDataUpdate)
    //搜索
    const hanledSearch = () => {
      debounceRefresh()
    }

    // 分页
    const handleCurrentChange = (val: number) => {
			search.current = val
      req()
			console.log('handleCurrentChange', val)
		}
    const handleSizeChange = (val: number) => {
      search.size = val
      req()
			console.log('handleSizeChange', val)
		}

    const req = () => {
      search.loading = true
    request.sendRequest({
      address: 'warehouse/supplier/getSupplierPage',
      params: search || {},
      success: (resp: RespData) => {
        if(resp.code !== 0) return ElMessage.error(resp.msg || '获取供应商管理列表失败')
        data.value = resp.data.records
        search.total = resp.data.total
        search.current = resp.data.current

        search.loading = false
      },
      fail: (resp: RespData) => {
        if(resp.code !== 0) return ElMessage.error(resp.msg || '获取供应商管理列表失败')
        
      },
      method: "POST",
    })
  }
    req()

    const debounceRefresh = debounce(req, 1000)

    /** 列表部分 -> 结束 */


    /** 抽屉部分开始 */
    const showWidget = useShowWidget;
    let showDrawer = ref(false)
    let showEditDrawer = ref(false)

    const handleClickDrawer = () => {
      groupDataAdd.value.forEach(i => i.value = '')
      showDrawer.value = true
    }

    const drawerClose = (type: string) => {
      ElMessageBox.confirm('此操作将关闭窗口, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {

				if(type === 'add') {
        showDrawer.value = false
        } else if (type === 'edit') {
          showEditDrawer.value = false
        }

			}).catch(() => {
					ElMessage({
						type: 'info',
						message: '已取消',
					});
      })
      
    }
    const cancel = (type: string) => {
      if(type === 'add') {
        showDrawer.value = false
      } else if (type === 'edit') {
        showEditDrawer.value = false
      }
    }

    // 修改
    const handleEditItem = (rowData: any) => {
      showEditDrawer.value = true
      search.id = rowData.id
      groupDataUpdate.value.forEach((item: any) => {
          Object.keys(rowData).forEach(i => {
            if(item.name === i) {
            console.log(rowData[item.name])
            item.value = rowData[item.name]
          }
        })
      })
    }
    // 删除
    const handleDelItem = (rowData: any) => {
      let id = rowData.id
      ElMessageBox.confirm('此操作将永久删除该项目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        request.sendRequest({
          address: `warehouse/supplier/delSupplier/${id}`,
          params: {},
          success: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg || '删除失败')
            ElMessage.success('删除成功')
            req()
          },
          fail: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg || '删除失败')
          },
          method: "POST",
        })
      }).catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消删除',
        });
      })
    }

    const save = (type: string) => {
      let params = {} as any 
      
      if(type === 'add') {
          groupDataAdd.value.forEach(item => {
            params[item.name] = item.value
          })

          request.sendRequest({
          address: 'warehouse/supplier/createSupplier',
          params,
          success: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg || '添加失败')
            ElMessage.success('添加成功')
            showDrawer.value = false
          },
          fail: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg || '添加失败')
          },
          method: "POST",
        })
      } else if (type === 'edit') {
        groupDataUpdate.value.forEach(item => {
            params[item.name] = item.value
        })
          params.id = search.id
          request.sendRequest({
          address: 'warehouse/supplier/updateSupplier',
          params,
          success: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg || '修改失败')
            ElMessage.success('修改成功')
            showEditDrawer.value = false
          },
          fail: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg || '修改失败')
          },
          method: "POST",
        })
      }
    }
    /** 抽屉部分结束 */
    return {
      ...toRefs(search),
      data,
      groupData,
      groupDataAdd,
      groupDataUpdate,
      hanledSearch,
      handleCurrentChange,
      handleSizeChange,
      handleDelItem,
      handleEditItem,


      showDrawer,
      showEditDrawer,
      showWidget,
      handleClickDrawer,
      drawerClose,
      cancel,
      save
    }
  }
})
</script>

<style>

</style>